import cheerio from "cheerio";
import {iFetcher} from '../iFetcher'
import {iArg} from "../iArg"
import { fetchRawData } from "./fetchRawData.js";



class UserRankFetcher implements iFetcher{
  public data:UserRank=new UserRank()
  public async fetch(arg:iArg):Promise<string>{
    const {contestType="algo",userName}=arg
    if (contestType ===undefined||userName===undefined){
        return ""
    }
    let htmlText=""
    htmlText=await fetchRawData(`https://atcoder.jp/users/${userName}?contestType=${contestType}&graph=rank`)
    if(htmlText===""){
      return ""
    }
    let $ = cheerio.load(htmlText);
    let dataText = $("script").eq(12).text();
    dataText = dataText.slice(17, dataText.length - 1);
    this.data.history = JSON.parse(dataText);
    let ele = $(".mt-2").find("tr").find("td");
    this.data.currentRank = ele.eq(0).text();
    this.data.lastComputed = ele.eq(4).text();
    let maxRank = Number.MAX_VALUE;
  
    for (let item of this.data.history) {
      item.EndTime=item.EndTime*1000
      if (item.Rank < maxRank) {
        maxRank = item.Rank;
      }
      item.ContestUrl = "https://atcoder.jp" + item.ContestUrl;
    }
    this.data.highestRank = maxRank;
    return JSON.stringify(this.data);
  }
  
}
class UserRank {
  constructor(
    currentRank: string = "",
    hightRank: number = 0,
    lastComputed: string = "",
    history: rankInfo[] = []
  ) {
    this.currentRank = currentRank;
    this.highestRank = hightRank;
    this.lastComputed = lastComputed;
    this.history = history;
  }
  currentRank: string;
  highestRank: number;
  lastComputed: string;
  history: rankInfo[];
}

interface rankInfo {
  EndTime: number;
  Rank: number;
  Rating: number;
  Competed: boolean;
  ContestName: string;
  ContestUrl: string;
}


export { UserRankFetcher };
